package cn.com.dcsgo.controller;

import cn.com.dcsgo.domain.Category;
import cn.com.dcsgo.dto.CategoryAddDTO;
import cn.com.dcsgo.dto.CategoryUpdateDTO;
import cn.com.dcsgo.model.Result;
import cn.com.dcsgo.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品分类相关接口
 *
 * @author Dcsgo
 * @since 2025/10/14 9:34
 */
@Tag(name = "产品分类相关接口")
@RestController
@RequestMapping("prod/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;

    @GetMapping("table")
    @PreAuthorize("hasAuthority('prod:category:page')")
    @Operation(summary = "获取所有分类信息", description = "返回数据不具有层级关系，按父分类ID和排序数升序排序")
    public Result<List<Category>> getOrderedCategoryTable() {
        List<Category> categoryList = categoryService.getOrderedCategoryTable();
        return Result.success(categoryList);
    }

    @GetMapping("listCategory")
    @PreAuthorize("hasAuthority('prod:category:page')")
    @Operation(summary = "获取所有正常分类信息", description = "返回数据不具有层级关系，数据状态为正常，按父分类ID和排序数升序排序")
    public Result<List<Category>> getOrderedTopCategoryList() {
        List<Category> categoryList = categoryService.getOrderedNormalCategoryList();
        return Result.success(categoryList);
    }

    @PostMapping
    @PreAuthorize("hasAuthority('prod:category:save')")
    @Operation(summary = "添加分类")
    public Result<Void> addCategory(@Validated @RequestBody CategoryAddDTO categoryAddDTO) {
        return Result.handle(categoryService.addCategory(categoryAddDTO));
    }

    @GetMapping("info/{categoryId}")
    @PreAuthorize("hasAuthority('prod:category:info')")
    @Operation(summary = "获取分类信息")
    public Result<Category> getCategoryInfo(@PathVariable Long categoryId) {
        return Result.success(categoryService.getById(categoryId));
    }

    @PutMapping
    @PreAuthorize("hasAuthority('prod:category:update')")
    @Operation(summary = "修改分类")
    public Result<Void> updateCategory(@Validated @RequestBody CategoryUpdateDTO categoryUpdateDTO){
        return Result.handle(categoryService.updateById(categoryUpdateDTO));
    }

    @DeleteMapping("{categoryId}")
    @PreAuthorize("hasAuthority('prod:category:delete')")
    @Operation(summary = "删除分类",description = "有子分类的，状态不为下线的不允许删除")
    public Result<Void> deleteCategory(@PathVariable Long categoryId) {
        return Result.handle(categoryService.carefulRemoveById(categoryId));
    }
}
